package com.sgcc.activiti.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.sgcc.activiti.domain.*;
import com.sgcc.activiti.mapper.OContentAppMapper;
import com.sgcc.activiti.service.*;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.text.UUID;
import com.sgcc.common.core.utils.DateUtils;
import com.sgcc.common.core.utils.FastJsonUtil;
import com.sgcc.common.core.utils.HttpClientUtil;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.redis.service.RedisService;
import com.sgcc.common.security.service.TokenService;
import com.sgcc.system.api.RemoteDictDataService;
import com.sgcc.system.api.domain.SysDictData;
import com.sgcc.activiti.mapper.OContentAppSchemaMapper;
import com.sgcc.system.api.domain.SysRole;
import com.sgcc.system.api.domain.SysUser;
import com.sgcc.system.api.model.LoginUser;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.util.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.sgcc.activiti.mapper.OContentAppSchemaMapper;
import com.sgcc.activiti.domain.OContentAppSchema;
import com.sgcc.activiti.service.IOContentAppSchemaService;
import org.springframework.util.CollectionUtils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 资讯查询Service业务层处理
 *
 * @author sgcc
 * @date 2021-04-07
 */
@Service
public class OContentAppSchemaServiceImpl implements IOContentAppSchemaService {
    @Autowired
    private OContentAppSchemaMapper oContentAppSchemaMapper;

    @Autowired
    private OContentAppMapper oContentAppMapper;

    @Autowired
    private RemoteDictDataService remoteDictDataService;

    @Autowired
    private IOContentAppPicService oContentAppPicService;

    @Autowired
    private IOInterfaceIndexService interfaceIndexService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IProcessService processService;

    @Autowired
    private IOContentAdPicService oContentAdPicService;

    @Value("${isTest}")
    private Boolean isTest;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询资讯查询
     *
     * @param id 资讯查询ID
     * @return 资讯查询
     */
    @Override
    public OContentAppSchema selectOContentAppSchemaById(String id) {
        OContentAppSchema oContentAppSchema = oContentAppSchemaMapper.selectOContentAppSchemaById(id);
        if (oContentAppSchema != null) {
            String bannerId = oContentAppSchema.getBannerpicId();
            String contentPicids = oContentAppSchema.getContentPicids();
            if (StringUtils.isNotBlank(bannerId)) {
                OContentAppPic oContentAppPic = oContentAppPicService.selectOContentAppPicById(bannerId);
                if (oContentAppPic != null) {
//                    oContentAppSchema.setBannerUrl(oContentAppPic.getPicUrl());
                }
            }
            if (StringUtils.isNotBlank(contentPicids)) {
//				List<PicDto> picDtoList = Lists.newArrayList();
//				String[] picids = contentPicids.split(",");
//				for(int i=0;i<picids.length;i++){
//					OContentAppPic pic = oContentAppPicService.get(picids[i]);
//					picDtoList.add(new PicDto(pic.getPicUrl(),pic.getSortNo()));
//				}
//				oContentAppSchema.setContentPicUrls(picDtoList);
                String picUrls = "";
                String[] picids = contentPicids.split(",");
                for (int i = 0; i < picids.length; i++) {
                    OContentAppPic pic = oContentAppPicService.selectOContentAppPicById(picids[i]);
                    if (pic != null) {
                        picUrls = picUrls + "|" + pic.getPicUrl();
                    }
                }
//                oContentAppSchema.setContentPicUrls(picUrls);
            }
        }
        return oContentAppSchemaMapper.selectOContentAppSchemaById(id);
    }

    /**
     * 查询资讯查询列表
     *
     * @param oContentAppSchema 资讯查询
     * @return 资讯查询
     */
    @Override
    public List<OContentAppSchema> selectOContentAppSchemaList(OContentAppSchema oContentAppSchema) {
        List<OContentAppSchema> list = oContentAppSchemaMapper.selectOContentAppSchemaList(oContentAppSchema);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    if (null == item.getProcessKey()) {
                        item.setType("todo");
                    }
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    /**
     * 新增资讯查询
     *
     * @param oContentAppSchema 资讯查询
     * @return 结果
     */
    @Autowired
    private RedisService redisService;
    private String time = DateUtils.dateTime();

    @Override
    public int insertOContentAppSchema(OContentAppSchema oContentAppSchema) {
        Integer num = redisService.getCacheObject("activiti:OContentAppSchemaServiceImpl:insertOContentAppSchema");
        if (null == num) {
            num = 0;
        }
//        OContentApp contentApp=oContentAppMapper.selectOContentAppById(oContentAppSchema.getId());
        num++;
        if (!time.equals(DateUtils.dateTime())) {
            num = 1;
            time = DateUtils.dateTime();
        }
        redisService.setCacheObject("activiti:OContentAppSchemaServiceImpl:insertOContentAppSchema", num);

        if (oContentAppSchema.getNewId() == null) {
            OContentApp oContentApp = new OContentApp();
            BeanUtils.copyProperties(oContentAppSchema, oContentApp);
            oContentApp.setAdvissueState("1");
            oContentApp.setDelFlag("0");
            oContentApp.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            oContentApp.setAppId(oContentApp.getId());
            oContentAppMapper.insertOContentApp(oContentApp);
            oContentAppSchema.setAppId(oContentApp.getId());
        }


        NumberFormat f = new DecimalFormat("00000");
        String id = DateUtils.dateTimeNow() + f.format(num);
        oContentAppSchema.setId(id);

        int i = oContentAppSchemaMapper.insertOContentAppSchema(oContentAppSchema);
        if (i > 0) {
//            contentApp.setAppNo(id);
//            oContentAppMapper.updateOContentApp(contentApp);
            OContentAppSchema obj = oContentAppSchemaMapper.selectOContentAppSchemaById(id);
            try {
                processService.submitApply(obj, "app");
            } catch (Exception e) {
                e.printStackTrace();
            }
            oContentAppSchemaMapper.updateOContentAppSchema(obj);
        }
        return i;
    }

    /**
     * 修改资讯查询
     *
     * @param oContentAppSchema 资讯查询
     * @return 结果
     */
    @Override
    public int updateOContentAppSchema(OContentAppSchema oContentAppSchema) {
        return oContentAppSchemaMapper.updateOContentAppSchema(oContentAppSchema);
    }

    /**
     * 批量删除资讯查询
     *
     * @param ids 需要删除的资讯查询ID
     * @return 结果
     */
    @Override
    public int deleteOContentAppSchemaByIds(String[] ids) {
        return oContentAppSchemaMapper.deleteOContentAppSchemaByIds(ids);
    }

    /**
     * 删除资讯查询信息
     *
     * @param id 资讯查询ID
     * @return 结果
     */
    @Override
    public int deleteOContentAppSchemaById(String id) {
        return oContentAppSchemaMapper.deleteOContentAppSchemaById(id);
    }

    @Override
    public List<TxtDto> sceneDta(String id) throws Exception {
        OContentAppSchema oContentAppSchema = selectOContentAppSchemaById(id);
//        String rpcInterface = DictUtils.getDictValue("统一业务接口", "rpcInterface", "test");
        OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101440");
        String rpcInterface = "";
        if (null != oInterfaceIndex && null != oInterfaceIndex.getInterfaceAdress()) {
            rpcInterface = oInterfaceIndex.getInterfaceAdress();
        }
        List<TxtDto> list = Lists.newArrayList();
        if (isTest) {
            list.add(new TxtDto("", ""));
            list.add(new TxtDto("1", "频道1"));
            list.add(new TxtDto("2", "频道2"));
            list.add(new TxtDto("3", "频道3"));
            return list;
        } else {
            String params = "";
            int resultCode = 0;
            String message = "";
            //构建参数
            /**
             * {
             "serviceCode":"0101440",
             "target":"33101",
             "source":"01",
             "data":{
             "platformId":"330000",
             "serialNum":"d567cf117aa24c41b07e6ddd25a4b409",
             "serviceType":"业务类型"
             }
             * }
             */
            Map paramsData = new HashMap();
            paramsData.put("platformId", "350000");
            if (oContentAppSchema != null) {
                paramsData.put("serialNum", oContentAppSchema.getId());
            }
            paramsData.put("serviceType", "01");

            Map map = new HashMap();
            map.put("serviceCode", "0101440");
            map.put("source", "SGAPP");
            map.put("target", "35101");
            map.put("data", paramsData);
            params = FastJsonUtil.toJSONString(map);
            String rpcResultStr = HttpClientUtil.sendJsonStr(rpcInterface, params).getData();
            //解析返回值
            OContentAppResult oContentAppResult = FastJsonUtil.toBean(rpcResultStr, OContentAppResult.class);
            resultCode = oContentAppResult.getCode();
            message = oContentAppResult.getMessage();
            if (1 == resultCode) {
                JSONObject data = (JSONObject) oContentAppResult.getData();
                SceneDataDto sceneData = data.toJavaObject(SceneDataDto.class);
                List<SceneDto> sceneDtos = sceneData.getData();
                if (CollectionUtil.isNotEmpty(sceneDtos)) {
                    for (SceneDto dto : sceneDtos) {
                        list.add(new TxtDto(dto.getChannelId(), dto.getChannelName()));
                    }
                }
                return list;
            } else {
                throw new Exception("频道列表信息获取失败");
            }
        }
    }

    @Override
    public List<SysDictData> getValueByType(String flowType) {
        AjaxResult ajaxResult = remoteDictDataService.dictType(flowType);
        List<SysDictData> sysDictDataList = (List) ajaxResult.get("data");
        return sysDictDataList;
    }

    @Override
    public void saveEx(OContentAppSchema oContentAppSchema) throws Exception {
        List<OContentAppPic> picList = Lists.newArrayList();
        String bannerUrl = oContentAppSchema.getBannerUrl();
        if (StringUtils.isNotBlank(bannerUrl)) {
            OContentAppPic pic = new OContentAppPic();
            pic.setPicType("0");
            pic.setPicUrl(bannerUrl);
            picList.add(pic);
        }
        String contentPicUrls = oContentAppSchema.getContentPicUrls();
        if (StringUtils.isNotBlank(contentPicUrls)) {
            String[] urls = contentPicUrls.substring(1).split("\\|");
            if (urls != null && urls.length > 0) {
                for (int i = 0; i < urls.length; i++) {
                    OContentAppPic conPic = new OContentAppPic();
                    conPic.setPicType("1");
                    conPic.setPicUrl(urls[i]);
                    conPic.setSortNo(i);
                    picList.add(conPic);
                }
            }
        }

        if (CollectionUtil.isNotEmpty(picList)) {
            oContentAppSchema.setBannerpicId(null);
            oContentAppSchema.setContentPicids(null);
            for (OContentAppPic appPic : picList) {
                appPic = oContentAppPicService.uploadImg(appPic);
                oContentAppPicService.insertOContentAppPic(appPic);
                if ("0".equals(appPic.getPicType())) {
                    oContentAppSchema.setBannerpicId(appPic.getId());
                } else {
                    oContentAppSchema.setContentPicids(StringUtils.isBlank(oContentAppSchema.getContentPicids()) ? appPic.getId() : (oContentAppSchema.getContentPicids() + "," + appPic.getId()));
                }
            }
        }
    }

    @Override
    public AjaxResult publish(OContentAppSchema oContentAppSchema) throws Exception {
        String id = oContentAppSchema.getId();
        if (StringUtils.isBlank(id)) {
            return AjaxResult.error(400, "缺少参数");
        }
        oContentAppSchema = selectOContentAppSchemaById(id);
        // String rpcInterface = DictUtils.getDictValue("统一业务接口", "rpcInterface", "test");
        OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101115");
        String rpcInterface = "test";
        if (null != oInterfaceIndex && null != oInterfaceIndex.getInterfaceAdress()) {
            rpcInterface = oInterfaceIndex.getInterfaceAdress();
        }
        String serviceType = oContentAppSchema.getServiceType();
        int resultCode = 0;
        if (isTest) {
            long time = System.currentTimeMillis();
            Date date1 = new Date(time);
        /*LoginUser loginUser = tokenService.getLoginUser();
        SysUser user = loginUser.getSysUser();
        String procInsId = oContentAppSchema.getProcInsId();*/
            HashMap<String, Object> var = new HashMap<>();
            var.put("edit", 1);
            //编辑表单
            // 当前环节，包括流程的环节，有结束、终止等
            oContentAppSchema.setActName("资讯发布待反馈");
            //流采用标准编码 flowType 01待提交 02待审核 03待发布 04待反馈 05发布失败 06结束 07待提交-审核不通过 08终止
            oContentAppSchema.setFlowType("04");
            oContentAppSchema.setArriveTime(date1);
//        insertOContentAppSchema(oContentAppSchema);
            try {
                processService.richProcessField(oContentAppSchema);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject obj = new JSONObject();
            obj.put("comment", "同意");
            obj.put("pass", true);
            obj.put("publishResults", "01");
            obj.put("formData", oContentAppSchema);
            processService.complete(oContentAppSchema.getTaskId(), oContentAppSchema.getInstanceId(), obj.toJSONString());
            return AjaxResult.success("资讯流程发布待反馈");
        }


        if ("01".equals(serviceType)) {
            if ("test".equals(rpcInterface)) {
                resultCode = 1;
            } else {
                String params = "";
                //构建参数
                /**
                 * {
                 "serviceCode":"0101115",
                 "target":"35101",
                 "source":"SGAPP",
                 "data":{
                 "platformId":"35101",
                 "serialNum":"d567cf117aa24c41b07e6ddd25a4b409",
                 "serviceType":"01",
                 "contentTitle":"心的乌镇来了就不曾离开-0",
                 "contentType":"0",
                 "mationType":"1",
                 "contentScene":"3",
                 "contentDetails":"资讯描述",
                 "bannerPicId":"001a3de7edd247fb9984fc8752689772",
                 "releaseScope":"35101",
                 "pulishType":"浙江精1",
                 "contentApp":"<div><p><img src=\"001a3de7edd247fb9984fc8752689772\" alt=\"\"></p><p>报道称，该论坛有超过50家的日本企业巨头、中日企域等发挥相互优势，开拓海外市场。</p><div></div></div>",
                 "contentIsStick":"1",
                 "contentPicIds":"001a3de7edd247fb9984fc8752689772,1"
                 }
                 * }
                 */
                Map paramsData = new HashMap();
                String contentPicids = oContentAppSchema.getContentPicids();
                String appIds = "";
//                if (StringUtils.isNotBlank(contentPicids)) {
//                    String[] picids = contentPicids.split(",");
//                    for (int i = 0; i < picids.length; i++) {
////                        OContentAppPic pic = oContentAppPicService.selectOContentAppPicById(picids[i]);
//                        R<OContentAdPic> adPic1 = oContentAdPicService.uploadImg("01", picids[i], "01", "02");
//                        if (adPic1.getCode() != 200) {
//                            return AjaxResult.error(adPic1.getMsg());
//                        }
//                        if (adPic1 != null) {
//                            if (i == 0) {
//                                appIds=adPic1.getData().getPicId();
//                            }else{
//                                appIds = appIds + "," + adPic1.getData().getPicId();
//                            }
//                        }
//                    }
//                }
                paramsData.put("platformId", "350000");
                paramsData.put("serialNum", oContentAppSchema.getId());
                paramsData.put("serviceType", "04");
                paramsData.put("contentTitle", oContentAppSchema.getContentTitle());
                paramsData.put("contentType", "0");
                paramsData.put("mationType", oContentAppSchema.getMationType());
                paramsData.put("contentScene", oContentAppSchema.getContentScene());
                paramsData.put("contentDetails", oContentAppSchema.getContentDetails());
                paramsData.put("releaseScope", "350000");
                paramsData.put("pulishType", oContentAppSchema.getPublishType());

                paramsData.put("contentInformtion", oContentAppSchema.getContentinFormtion());
                paramsData.put("contentIsStick", "1");
                R<OContentAdPic> adPic2 = oContentAdPicService.uploadImg("01", oContentAppSchema.getBannerpicId(), "01", "02");
                if (adPic2.getCode() != 200) {
                    return AjaxResult.error(adPic2.getMsg());
                }
                paramsData.put("bannerPicId", adPic2.getData().getPicId());
//                paramsData.put("bannerPicId",oContentAppSchema.getBannerpicId());

                String detail = oContentAppSchema.getContentApp();
                String ids = "";

                List<String> pics = getImgStr(detail);

                for (int i = 0; i < pics.size(); i++) {
                    String pic = pics.get(i);
                    logger.info("截取图片地址："+pic);
            R<OContentAdPic> adPic1 = oContentAdPicService.uploadImg("01", pic, "01", "02");
                    String imgurl =  adPic1.getData().getPicId();
                    detail = detail.replace(pic, imgurl);
                    if (adPic1 != null) {
                        if (i == 0) {
                            ids = adPic1.getData().getPicId();
                        } else {
                            ids = ids + "," + adPic1.getData().getPicId();
                        }
                    }
                }


                paramsData.put("contentPicIds", ids);
                paramsData.put("contentApp", detail);
                Map map = new HashMap();
                map.put("serviceCode", "0101115");
                map.put("source", "SGAPP");
                map.put("target", "35101");
                map.put("data", paramsData);
                params = FastJsonUtil.toJSONString(map);
                String rpcResultStr = HttpClientUtil.sendJsonStr(rpcInterface, params).getData();
                //解析返回值
                R oContentAdResult = FastJsonUtil.toBean(rpcResultStr, R.class);
                resultCode = oContentAdResult.getCode();
            }
        } else if ("02".equals(serviceType)) {
            if ("test".equals(rpcInterface)) {
                resultCode = 1;
            } else {
                String params = "";
                //构建参数
                /**
                 * {
                 "serviceCode":"0101123",
                 "target":"35101",
                 "source":"SGAPP",
                 "data":{
                 "platformId":"35101",
                 "serialNum":"d567cf117aa24c41b07e6ddd25a4b409",
                 "serviceType":"02",
                 "contentTitle":"心的乌镇来了就不曾离开-0",
                 "contentType":"0",
                 "mationType":"1",
                 "contentScene":"3",
                 "contentDetails":"资讯描述",
                 "bannerPicId":"001a3de7edd247fb9984fc8752689772",
                 "releaseScope":"35101",
                 "pulishType":"浙江精1",
                 "contentApp":"<div><p><img src=\"001a3de7edd247fb9984fc8752689772\" alt=\"\"></p><p>报道称，该论坛有超过50家的日本企业巨头、中日企域等发挥相互优势，开拓海外市场。</p><div></div></div>",
                 "contentIsStick":"1",
                 "contentPicIds":"001a3de7edd247fb9984fc8752689772,1"
                 }
                 * }
                 */
                Map paramsData = new HashMap();
                String contentPicids = oContentAppSchema.getContentPicids();
                String appIds = "";
                if (StringUtils.isNotBlank(contentPicids)) {
                    String[] picids = contentPicids.split(",");
                    for (int i = 0; i < picids.length; i++) {
//                        OContentAppPic pic = oContentAppPicService.selectOContentAppPicById(picids[i]);
                        R<OContentAdPic> adPic1 = oContentAdPicService.uploadImg("01", picids[i], "01", "02");
                        if (adPic1.getCode() != 200) {
                            return AjaxResult.error(adPic1.getMsg());
                        }
                        if (adPic1 != null) {
                            if (i == 0) {
                                appIds = adPic1.getData().getPicId();
                            } else {
                                appIds = appIds + "," + adPic1.getData().getPicId();
                            }
                        }
                    }
                }
                paramsData.put("platformId", "350000");
                paramsData.put("serialNum", oContentAppSchema.getId());
                paramsData.put("serviceType", "05");
                paramsData.put("contentId", oContentAppSchema.getNewId());
                paramsData.put("contentTitle", oContentAppSchema.getContentTitle());
                paramsData.put("contentType", "0");
                paramsData.put("mationType", oContentAppSchema.getMationType());
                paramsData.put("contentScene", oContentAppSchema.getContentScene());
                paramsData.put("contentDetails", oContentAppSchema.getContentDetails());
                paramsData.put("releaseScope", "350000");
                paramsData.put("pulishType", oContentAppSchema.getPublishType());
//                paramsData.put("contentApp", oContentAppSchema.getContentApp());
                paramsData.put("contentAuthor", oContentAppSchema.getContentAuthor());
                paramsData.put("contentInformtion", oContentAppSchema.getContentinFormtion());
                paramsData.put("contentIsStick", "1");
//                paramsData.put("bannerPicId", oContentAppPicService.selectOContentAppPicById(oContentAppSchema.getBannerpicId())==null?null:oContentAppPicService.selectOContentAppPicById(oContentAppSchema.getBannerpicId()).getAppId());
                R<OContentAdPic> adPic2 = oContentAdPicService.uploadImg("01", oContentAppSchema.getBannerpicId(), "02", "02");
                if (adPic2.getCode() != 200) {
                    return AjaxResult.error(adPic2.getMsg());
                }
                paramsData.put("bannerPicId", adPic2.getData().getPicId());
//                paramsData.put("bannerPicId", oContentAppSchema.getBannerpicId());

                String detail = oContentAppSchema.getContentApp();
                String ids = "";

                List<String> pics = getImgStr(detail);

                for (int i = 0; i < pics.size(); i++) {
                    String pic = pics.get(i);
                    R<OContentAdPic> adPic1 = oContentAdPicService.uploadImg("01", pic, "01", "02");
                    String imgurl = adPic1.getData().getPicId() ;
                    detail = detail.replace(pic, imgurl);
                    if (adPic1 != null) {
                        if (i == 0) {
                            ids = adPic1.getData().getPicId();
                        } else {
                            ids = ids + "," + adPic1.getData().getPicId();
                        }
                    }
                }


                paramsData.put("contentPicIds", ids);
                paramsData.put("contentApp", detail);

                Map map = new HashMap();
                map.put("serviceCode", "0101123");
                map.put("source", "SGAPP");
                map.put("target", "35101");
                map.put("data", paramsData);
                params = FastJsonUtil.toJSONString(map);
                String rpcResultStr = HttpClientUtil.sendJsonStr(rpcInterface, params).getData();
                //解析返回值
                R r = FastJsonUtil.toBean(rpcResultStr, R.class);
                resultCode = r.getCode();
            }
        } else {
            throw new Exception("资讯维护类型错误");
        }
        if (1 != resultCode) {
            throw new Exception("远程调用接收参数失败");
        }
        long time = System.currentTimeMillis();
        Date date1 = new Date(time);
        /*LoginUser loginUser = tokenService.getLoginUser();
        SysUser user = loginUser.getSysUser();
        String procInsId = oContentAppSchema.getProcInsId();*/
        HashMap<String, Object> var = new HashMap<>();
        var.put("edit", 1);
        //编辑表单
        // 当前环节，包括流程的环节，有结束、终止等
        oContentAppSchema.setActName("资讯发布待反馈");
        //流采用标准编码 flowType 01待提交 02待审核 03待发布 04待反馈 05发布失败 06结束 07待提交-审核不通过 08终止
        oContentAppSchema.setFlowType("04");
        oContentAppSchema.setArriveTime(date1);
//        insertOContentAppSchema(oContentAppSchema);
        try {
            processService.richProcessField(oContentAppSchema);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject obj = new JSONObject();
        obj.put("comment", "同意");
        obj.put("pass", true);
        obj.put("publishResults", "01");
        obj.put("formData", oContentAppSchema);
        processService.complete(oContentAppSchema.getTaskId(), oContentAppSchema.getInstanceId(), obj.toJSONString());
        return AjaxResult.success("资讯流程发布待反馈");
    }

    @Override
    public AjaxResult audit(OContentAppSchema oContentAppSchema, String auditType, String comment) throws Exception {
        String id = oContentAppSchema.getId();
        if (StringUtils.isBlank(id)) {
            return AjaxResult.error(400, "缺少参数");
        }
        oContentAppSchema = selectOContentAppSchemaById(id);
        long time = System.currentTimeMillis();
        Date date1 = new Date(time);
        HashMap<String, Object> var = new HashMap<>();
        //维护类型，操作类型：serviceType 01	新增 02	变更 03	下架
        String serviceType = oContentAppSchema.getServiceType();
        String procInsId = oContentAppSchema.getProcInsId();
        String newId = oContentAppSchema.getNewId();
        logger.info("资讯审核：类型：" + serviceType);
        if ("0".equals(auditType)) {
            //auditType 0,审核不通过
            //审核不通过
            if ("01".equals(serviceType) || "02".equals(serviceType) || "03".equals(serviceType)) {
                //新增审核
                //流程参数
                var.put("auditType", 0);

                //编辑表单
                // 当前环节，包括流程的环节，有结束、终止等
                oContentAppSchema.setActName("资讯维护");
                //流采用标准编码 flowType 01待提交 02待审核 03待发布 04待反馈 05发布失败 06结束 07待提交-审核不通过 08终止
                oContentAppSchema.setFlowType("07");
                oContentAppSchema.setArriveTime(date1);
                insertOContentAppSchema(oContentAppSchema);
            }
        } else if ("1".equals(auditType)) {
            //auditType 1,审核通过
            //审核通过
            if ("01".equals(serviceType) || "02".equals(serviceType)) {
                //新增审核
                var.put("auditType", 1);

                //编辑表单
                // 当前环节，包括流程的环节，有结束、终止等
                oContentAppSchema.setActName("资讯发布");
                //流采用标准编码 flowType 01待提交 02待审核 03待发布 04待反馈 05发布失败 06结束 07待提交-审核不通过 08终止
                oContentAppSchema.setFlowType("03");
                oContentAppSchema.setArriveTime(date1);
                insertOContentAppSchema(oContentAppSchema);
            } else if ("03".equals(serviceType)) {
                logger.info("资讯审核下架审核成功");
                //下架审核
                var.put("auditType", 2);
                int resultCode = 0;
                /**
                 * 调用远程接口，下架该广告
                 */
//                String rpcInterface = DictUtils.getDictValue("统一业务接口", "rpcInterface", "test");
                OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101127");
                String rpcInterface = "test";
                if (null != oInterfaceIndex && null != oInterfaceIndex.getInterfaceAdress()) {
                    rpcInterface = oInterfaceIndex.getInterfaceAdress();
                } else {
                    return AjaxResult.error("0101127接口未配置");
                }
                if ("test".equals(rpcInterface)) {
                    resultCode = 1;
                } else {
                    logger.info("执行资讯审核下架方法2");
                    String params = "";
                    //构建参数
                    /**
                     * {
                     "serviceCode":"0101127",
                     "target":"35101",
                     "source":"SGAPP",
                     "data":{"platformId":"35101",
                     "serialNum":"1111",
                     "serviceType":"03",
                     "releaseScope":"330000",
                     "contentId":"93e6c04bb62d4714a9b8cfd00707a023"}
                     *   }
                     * }
                     */
                    Map paramsData = new HashMap();
                    paramsData.put("serialNum", oContentAppSchema.getId());
                    paramsData.put("serviceType", "06");
                    paramsData.put("platformId", "350000");
                    paramsData.put("contentId", oContentAppSchema.getAppId());
                    paramsData.put("releaseScope", "350000");
                    /*CommonParm commonParm = new CommonParm();
                    commonParm.setTarget("35101");
                    commonParm.setSource("SGAPP");
                    commonParm.setServiceCode("0101127");
                    commonParm.setData(paramsData);
                    params = FastJsonUtil.toJSONString(commonParm);*/
                    Map map = new HashMap();
                    map.put("serviceCode", "0101127");
                    map.put("source", "SGAPP");
                    map.put("target", "35101");
                    map.put("data", paramsData);
                    params = FastJsonUtil.toJSONString(map);
                    String rpcResultStr = HttpClientUtil.sendJsonStr(rpcInterface, params).getData();
                    //解析返回值
                    R r = FastJsonUtil.toBean(rpcResultStr, R.class);
                    resultCode = r.getCode();
                }
                if (1 == resultCode) {
                    //编辑表单
                    // 当前环节，包括流程的环节，有结束、终止等
                    oContentAppSchema.setActName("下架待反馈");
                    //流采用标准编码 flowType 01待提交 02待审核 03待发布 04待反馈 05发布失败 06结束 07待提交-审核不通过 08终止 09失败结束
                    oContentAppSchema.setFlowType("11");
                    oContentAppSchema.setArriveTime(date1);
                    insertOContentAppSchema(oContentAppSchema);
                } else {
                    throw new Exception("远程接收参数失败");
                }
            }
        }
        return AjaxResult.success("资讯流程审核成功!");
    }

    @Override
    public List<OContentAppSchema> selectOContentAppSchemaListProcess(OContentAppSchema oContentAppSchema) {
        SysUser user = tokenService.getLoginUser().getSysUser();
        List<String> ids = new ArrayList<String>();
        for (SysRole role : user.getRoles()) {
            ids.add(role.getRoleKey());
        }
        oContentAppSchema.setRoleKey(ids);
        oContentAppSchema.setAssignee(user.getUserName());

        List<OContentAppSchema> list = oContentAppSchemaMapper.selectOContentAppSchemaListProcess(oContentAppSchema);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
//                    if (null == item.getProcessKey()) {
                    item.setType("todo");
//                    }
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    @Override
    public List<OContentAppSchema> selectOContentAppSchemaSubmitist(OContentAppSchema oContentAppSchema) {

        List<OContentAppSchema> list = oContentAppSchemaMapper.selectOContentAppSchemaSubmitist(oContentAppSchema);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
//                    if (null == item.getProcessKey()) {
//                    item.setType("todo");
//                    }
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
    }

    @Override
    public Integer selectOContentAppByNewId(String newId) {
        return oContentAppSchemaMapper.selectOContentAppByNewId(newId);
    }


//    public static void main(String[] args) {
//        String detail = "<p>fj_zx_test_0604_04< img src=\"https://wsgw-oss-test-001.oss-fj-1-a.ops.sgmc.sgcc.com.cn//qr/1622801382670OpenFile (1).jpg\">< img src=\"https://wsgw-oss-test-001.oss-fj-1-a.ops.sgmc.sgcc.com.cn//qr/1622801390071OpenFile.JPG\"></p >";
//        String ids = "";
//
//        List<String> pics = getImgStr(detail);
//
//        for (int i = 0; i < pics.size(); i++) {
//            String pic = pics.get(i);
////            R<OContentAdPic> adPic1 = oContentAdPicService.uploadImg("01", pic, "01", "02");
//            OContentAdPic oContentAdPic = new OContentAdPic();
//            oContentAdPic.setPicId("1234");
//            R<OContentAdPic> adPic1 = R.ok(oContentAdPic);
//            String imgurl="/omg-static/"+adPic1.getData().getPicId()+".jpg";
//            detail=    detail.replace(pic,imgurl);
//            if (adPic1 != null) {
//                if (i == 0) {
//                    ids=adPic1.getData().getPicId();
//                }else{
//                    ids = ids + "," + adPic1.getData().getPicId();
//                }
//            }
//        }
//
//    }


    /**
     * 得到网页中图片的地址
     */
    public static List<String> getImgStr(String htmlStr) {
        List<String> pics = new ArrayList<String>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }
}
